package index

import (
	"engine/dto"
	emodel "engine/model"
	"github.com/gin-gonic/gin"
	"io"
	"lib/db"
	"lib/log"
	"lib/response"
	"lib/task"
	"net/http"
	"strconv"
	"time"
)

// SessionData stores verification code related data
type SessionData struct {
	TuxingYzmX          int
	TuxingYzmY          int
	TuxingYzmImg        string
	TuxingYzmMoban      string
	TuxingYzmOpacity    int
	TuxingYzmTime       int64
	TuxingYzmErrorCishu int
	TuxingYzmVerified   bool
}

// Global session store (in production, use Redis or other proper session store)
var reqMap = make(map[string]string)

type reqdata struct {
	Type      string `json:"type" binding:"required" size:"20"`
	SessionId string `json:"session_id" binding:"required" size:"32"`
	Phone     string `json:"phone" binding:"required" size:"11"`
	Sid       string `json:"sid"`
	Abcde     string `json:"abcde"`
	X         string `json:"x"`
	Token     string `json:"token"`
}

func YzmPicHandler(c *gin.Context) {

	// Helper function to send JSON response
	queryParams := c.Request.URL.Query()

	// 目标URL
	targetURL := "https://api.simakuo.com/api/index/yzm_picss"

	// 创建新的请求
	req, err := http.NewRequest("GET", targetURL, nil)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 设置查询参数
	req.URL.RawQuery = queryParams.Encode()

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer resp.Body.Close()

	// 读取响应并返回给客户端
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.Data(resp.StatusCode, resp.Header.Get("Content-Type"), body)

}

type RefundResponse struct {
	MerchNo          string `json:"merch_no"`
	TransactionId    string `json:"transaction_id"`
	ChnTransactionId string `json:"chn_transaction_id"`
	OutTradeNo       string `json:"out_trade_no"`
	TotalAmount      string `json:"total_amount"`
	TransTime        string `json:"trans_time"`
	PayType          string `json:"pay_type"`
	OrderTime        string `json:"order_time"`
	RetMsg           string `json:"ret_msg"`
	RetCode          string `json:"ret_code"`
	Status           string `json:"status"`
	PayTime          string `json:"pay_time"`
}

func JiaLianPayNotify(c *gin.Context) {
	var req RefundResponse
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	}

	var myProorder *emodel.My_proorder
	myDb, err := myProorder.GetOrderDetailByOrderNo(req.OutTradeNo)
	if err != nil {
		c.JSON(200, gin.H{
			"ret_msg": err.Error(),
		})
		return
	}

	if myDb.Status == 0 && req.Status == "2" {

		//支付成功？
		nowTime := time.Now()
		myDb.ZfTime = &nowTime
		myDb.Status = 1

		if err = myDb.Updates(); err != nil {
			c.JSON(200, gin.H{
				"ret_msg": err.Error(),
			})
			return
		}
		user, err := dto.GetSysUserDetailById(myDb.Uid)
		if err != nil {
			log.Errorf("获取用户失败", err.Error())
		} else {
			if user != nil {

				endData := time.Now().AddDate(0, 0, 10)
				eDate := endData.Format("20060102")
				eDAteInt, _ := strconv.Atoi(eDate)

				nowTimeEnd := time.Now().Format("20060102")
				IntNow, _ := strconv.Atoi(nowTimeEnd)
				if user.OldLevel <= myDb.Pid && user.EndDate <= IntNow {
					db.GetDb().Table("my_user").Where("id=?", myDb.Uid).UpdateColumn("end_date", eDAteInt)
				}
			}

		}
	}

	c.JSON(200, gin.H{
		"ret_code": "00000",
	})
}

func SyncOrderEms(c *gin.Context) {
	var orderList []*emodel.My_proorder
	err := db.GetDb().Where("status>1 and status<3").Find(&orderList).Error
	if err != nil {
		response.OkData(c, "没有要处理的")
		return
	}
	if len(orderList) == 0 {
		response.OkData(c, "没有要处理的")
		return
	}

	for _, proorder := range orderList {
		task.SendEmsTask(proorder.Id, nil)
	}

}
